const app = getApp();
const Api = app.globalData.Api;
const wxApi = app.globalData.wxApi;
const util = app.globalData.util;
const historyStore = require('./historyStore');
const moduleMap = require('./moduleMap');
const selectImg = {
  open: '/images/search/select-open.png',
  close: '/images/search/select-close.png'
}
const modules = {
  topic: {"id":1,"name":"知识点"},
  book: {"id":2,"name":"课本"},
  practice: {"id":3,"name":"练习"},
  video: {"id":4,"name":"视频"}
};

let moduleAll = {
  id: 0,
  name: '全部'
}
Page({
  data: {
    hotSearchList: [], //热门搜索列表
    searchModules: [], //模块列表
    popviewShow: false, //底边模块面板是否显示
    searchValue: '', //输入的文本
    selectActiveModule: null, //当前选中模块
    selectImg: selectImg.open, //模块展开指向图片
    associationsShow: false, //是否显示联想列表
    associations: [], //联想列表
    histories: [], //搜索历史
    isSearchAll: true, //是否是全部搜索
    searchResultShow: false, //显示搜索结果
    searchResults: [], //对应模块下的结果
    activeModuleId: null, //当前选中模块
    topic: null, //知识点
    textbooks: [], //课本
    practices: [], //练习
    videos: [], //视频
    words: [],
    routeModule: 0,
    wordsMore: true
  },
  onLoad( options ) {
    wxApi.setNavTitle('全局搜索')
    this.topicAPI = require('../../net/topicApi')
    this.init( options );
  },
  init( options ) {
    let routeModuleName = options.name;
    
    this.subed = JSON.parse(options.subed || false) || false;
    this.wordsPageNo = 0;
    if ( routeModuleName ) {
      let routeModule = modules[ routeModuleName ];
      console.log( routeModule );
      if ( routeModule ) {
        this.setData({
          routeModule: routeModule
        })
        this.setSelectActiveModule( routeModule );
      } else {
        throw new Error( 'module name is error: ' + routeModuleName );
      }
    } else {
      this.setSelectActiveModule( moduleAll );
      this.loadSelectModules();
    }
  },
  /**
   * 输入值变化
   */
  onInputChange( e ) {
    let value = e.detail.value;
    console.log( value );
    this.setSearchValue( value );
    if ( value ) {
      this.openView('association', value);
    } else {
      this.openView('history');
    }
  },
  onBlur() {
    this.setData({
      selectImg: selectImg.open
    })
  },
  onFocus() {
    let searchValue = this.getSearchValue();
    this.closeSearchResult();
    if ( searchValue ) {
      this.initialModuleAllData();
      this.openView('association', searchValue);
    }
  },
  onNavBack() {
    wx.navigateBack();
  },
  onPractice( e ) {
    let practice = e.currentTarget.dataset.practice;
    wxApi.navigateTo('../common/nonsupport/nonsupport', {
      path: 'exercise',
      module: 'detail',
      type: practice.type,
      practiceId: practice.id
    })
  },
  /**
   * 底部模块面板打开
   */
  onModulesOpen() {
    this.openPopview();
  },
  /**
   * 选中模块
   */
  onModuleSelect( e ) {
    let dataset = e.currentTarget.dataset;
    let item = dataset.item;
    this.setSelectActiveModule( item );
    this.closePopview();
  },
  /**
   * 点击联想 搜索
   */
  onAssociationSearch( e ) {
    let value = e.currentTarget.dataset.text;
    this.setSearchValue( value );
    this.search( value );
  },
  /**
   * 点击历史 搜索
   */
  onHistorySearch( e ) {
    let value = e.detail;
    this.setSearchValue( value );
    this.search( value );
  },
  /**
   * 点击键盘 搜索
   */
  onTapSearch() {
    this.search( this.data.searchValue );
  },
  /**
   * 清除历史记录
   */
  onClearHistory() {
    let moduleId = this.getSelectActiveModule().id;
    this.setData({
      histories: []
    })
    historyStore.clearHistories( moduleId );
  },
  /**
   * 选中tabModule
   */
  onTabModuleSelected( e ) {
    console.log( 'tab module selected.' );
    let moduleId = e.currentTarget.dataset.moduleid;
    console.log( moduleId );
    this.setTabModuleId( moduleId );
  },
  /**
   * 课本详情
   */
  onBookDetail( e ) {
    let book = e.currentTarget.dataset.book;
    console.log( this.data.textbooks );
    let params = {
      id: book.id
    }
    wxApi.navigateTo('../book-detail/book-detail', params);
  },
  /**
   * 视频详情
   */
  onVideoDetail( e ) {
    let video = e.currentTarget.dataset.video;
    wxApi.navigateTo('../memory-detail/memory-detail', {
      id: video.id
    })
  },
  /**
   * 搜索
   */
  search( value ) {
    let moduleId = this.getSelectActiveModule().id;
    this.openView('result');
    this.addHistoryData( value );
    this.initialModuleAllData();
    switch( moduleId ) {
      case 0: {
        console.log( 'moduleAll: ')
        this.loadSearchAll( value, result => {
          console.log( result );
          this.setDataOfModuleAll( result );
        });
      } break;
      case 1: {
        console.log( 'moduleTopic: ' + moduleId );
        this.loadTopics( value );
      } break;
      case 2: {
        console.log( 'moduleBooks: ' + moduleId );
        this.loadTextbooks( value );
      } break;
      case 3: {
        console.log( 'modulePractice: ' + moduleId );
        this.loadPractices( value );
      } break;
      case 4: {
        console.log( 'moduleVideos: ' + moduleId );
        this.loadVideos( value );
      } break;
    }
  },
  /**
   * 设置 全部 模块数据
   */
  setDataOfModuleAll( result ) {
    let moduleId = this.getSelectActiveModule().id;
    // 默认请求下来的第一个模块的数据显示
    if ( result.modules.length ) {
      let firstModule = result.modules[ 0 ];
      this.setTabModuleId( firstModule.id );
    }
    this.setData({
      searchResults: result,
      topic: (result.topic && result.topic) || {},
      textbooks: (result.textbooks && result.textbooks.records) || [],
      videos: (result.videos && result.videos.records) || [],
      practices: (result.practices && result.practices.records) || []
    })
    
  },
  /**
   * 设置选中模块
   */
  setSelectActiveModule( moduleObj ) {
    this.setData({
      selectActiveModule: moduleObj
    })

    let searchValue = this.getSearchValue();
    this.setTabModuleId( moduleObj.id );
    this.loadHotData( moduleObj.id );
    this.loadHistoryData( moduleObj.id );
    // 如果存在搜索文本，则直接进行对应模块的搜索
    if ( searchValue ) {
      this.openView('result');
      this.search( searchValue );
    }
    
  },
  /**
   * 初始化 全部 模块的数据
   */
  initialModuleAllData() {
    console.log( 'clear moduleAll data.' );
    this.setData({
      topic: null, //知识点
      textbooks: [], //课本
      practices: [], //练习
      videos: [] //视频
    })
  },
  loadAssociations( keyword ) {
    let moduleId = this.getSelectActiveModule().id;
    // 全部 模块联想
    if ( moduleId == 0 ) {
      this.loadModuleAllAssociation( keyword );
    } else {
      this.loadModuleSingleAssociation( moduleId, keyword );
    }
    
  },
  loadTextbooks( value ) {
    let params = {
      searchText: value
    }
    if ( this.subed ) {
      params.conditions = [{
        "id": 1,
        "options": [{
          "id": "1"
        }]
      }]
    }
    Api.getBooks( params, res => {
      this.setData({
        textbooks: res.records
      })
    })
  },
  loadPractices( value ) {
    let params = {
      searchText: value
    }
    Api.practices( params, res => {
      this.setData({
        practices: res.records
      })
    })
  },
  loadVideos( value, pageNo ) {
    let params = {
      fuzzyName: value,
      pageNo: pageNo || 1
    }
    Api.memoryVideos( params, res => {
      console.log( res );
      this.setData({
        videos: res.records
      })
    })
  },
  loadModuleAllAssociation( keyword ) {
    Api.allSearchAssociation( keyword, associations => {
      this.setData({
        associations: associations
      })
    })
  },
  loadModuleSingleAssociation( moduleId, keyword ) {
    Api.moduleSearchAssociation(moduleId, keyword, associations => {
      this.setData({
        associations: associations
      })
    })
  },
  /**
   * 新增历史记录
   */
  addHistoryData( value ) {
    console.log( 'add history data: ' + value );
    let histories = this.data.histories;
    if ( !value ) return;
    let index = histories.indexOf( value );
    if ( index > -1 ) {
      histories.splice( index, 1 );
    }
    histories.unshift( value );
    this.setData({
      histories: histories
    })
    let moduleId = this.getSelectActiveModule().id;
    historyStore.setHistories( moduleId, histories );
    return histories;
  },
  
  /**
   * 历史记录
   */
  loadHistoryData( moduleId ) {
    console.log( 'load history data.' );
    historyStore.getHistories( moduleId, histories => {
      this.setData({
        histories: histories
      })
    })
  },
  
  /**
   * 热门搜索
   */
  loadHotData( moduleId ) {
    console.log( 'load hot data.' );
    if ( moduleId == 0 ) {
      moduleId = null;
    }
    Api.hotSearch( moduleId, list => {
      this.setData({
        hotSearchList: list
      })
    })
  },
  loadTopics( value ) {
    Api.getTopics( value, res => {
      this.setData({
        topic: res
      })
    })
  },
  /**
   * 模块列表
   */
  loadSelectModules() {
    console.log( 'load select modules.' )
    Api.searchModules( res => {
      console.log( res );
      res.unshift( moduleAll )
      this.setData({
        searchModules: res
      })
    })
  },
  /**
   * 搜索结果
   *
   * @param {*} value
   */
  loadSearchAll( value, callback ) {
    Api.allSearch( value, res => {
      callback( res );
    } )
  },
  onPopviewShowChange( e ) {
    this.closePopview();
  },
  closePopview() {
    this.setData({
      popviewShow: false,
      selectImg: selectImg.open
    })
  },
  openPopview() {
    this.setData({
      popviewShow: true,
      selectImg: selectImg.close
    })
  },
  openAssociations() {
    this.setData({
      associationsShow: true
    })
  },
  closeAssociations() {
    this.setData({
      associationsShow: false,
      associations: []
    })
  },
  openSearchResult() {
    this.setData({
      searchResultShow: true
    })
  },
  closeSearchResult() {
    this.setData({
      searchResultShow: false,
      searchResults: null,
    })
  },
  getSelectActiveModule() {
    return this.data.selectActiveModule;
  },

  setTabModuleId( id ) {
    this.setData({
      activeModuleId: id
    })
  },
  getTabModuleId() {

  },
  getSearchValue() {
    return this.data.searchValue;
  },
  setSearchValue( val ) {
    this.setData({
      searchValue: val
    })
  },
  openView( type, value ) {
    switch(type) {
      case 'history': {
        this.closeAssociations();
        this.closeSearchResult();
      } break;
      case 'association': {
        this.loadAssociations( value );
        this.closeSearchResult();
        this.openAssociations();
      } break;
      case 'result': {
        this.closeAssociations();
        this.openSearchResult();
      } break;
    }
  }
}) 